//
//  MessageListTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/15.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "MessageListTableViewController.h"
#import "MessageListTableViewCell.h"
#import "MessageDetailTableViewController.h"
#import "Puser.h"
#import "MessageListMode.h"
#import "UINavigationItem+Loading.h"
#import "UUMessage.h"
#import "NoItemView.h"

@interface MessageListTableViewController ()
{
    BOOL isshow;
}
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray *datalist;
@property (nonatomic,strong) NoItemView *notiem;

@end

@implementation MessageListTableViewController

+(instancetype)message{
    MessageListTableViewController *mlist=[[MessageListTableViewController alloc]initWithNibName:@"MessageListTableViewController" bundle:nil];
    mlist.hidesBottomBarWhenPushed=YES;
    return mlist;
}
-(NSMutableArray *)datalist{
    if ( _datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return  _datalist;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"消息通知";
    self.tableView.backgroundColor=bgGarycolor;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self setupnoItem];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    
    UINib *nib=[UINib nibWithNibName:@"MessageListTableViewCell" bundle:[NSBundle mainBundle]];
    
    [self.tableView registerNib:nib forCellReuseIdentifier:@"message"];
}

-(void)setupnoItem{
    self.notiem=[NoItemView viewWithType:MYMESSAGETYPE];
    [self.tableView addSubview:self.notiem];
    [self.notiem show];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    if (isshow) {
        NSDictionary * userInfo = [notification userInfo];
        
        NSDictionary *extras = [userInfo valueForKey:@"extras"];
        
        NSDictionary *content=extras[@"content"];
        [UUMessage setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     @"ID":@"id"
                     
                     };
        }];
        
        UUMessage *message=[UUMessage objectWithKeyValues:content];
        MessageListMode *mode=[[MessageListMode alloc]init];
        mode.fromId=message.toId;
        mode.toId=message.fromId;
        mode.fromType=message.toType;
        mode.ico=message.strIcon;
        mode.truename=message.strName;
        mode.sendtime=message.sendtime;
        mode.content=message.content;
        
        for (MessageListMode *nmode in self.datalist) {
            if ([nmode.toId isEqualToString:mode.toId]&&[nmode.fromType isEqualToString:mode.fromType]) {
                nmode.content=mode.content;
                nmode.sendtime=mode.sendtime;
                nmode.num=[NSString stringWithFormat:@"%ld",[nmode.num integerValue]+1];
                [self.tableView reloadData];
                return;
            }
        }
        mode.num=@"1";
        [self.datalist addObject:mode];
        [self.tableView reloadData];
        
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}
     ];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbg"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self getDataFromWeb];
    isshow=YES;
}

-(void)viewDidDisappear:(BOOL)animated{
    isshow=NO;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TRUE;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageListMode *mode=self.datalist[indexPath.row];
    
    [self deletemessage:mode];
}

-(void)deletemessage:(MessageListMode *)mode{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"delete_list";
    params[@"from_id"]=mode.fromId;
    params[@"from_type"]=mode.fromType;
    params[@"to_id"]=mode.toId;
    params[@"to_type"]=mode.toType;
    
    [PostUitls Post:messageurl parameters:params success:^(id response) {
        
        [self.datalist removeObject:mode];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}

-(void)getDataFromWeb{
    [self.datalist removeAllObjects];
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"con_list";
    
    int power=[self.user.power intValue];
    if (power<5) {
        params[@"uid"]=self.user.user_id;
        params[@"from_type"]=@"1";
    }else{
        params[@"uid"]=self.user.com_id;
        if (power==8) {
            params[@"from_type"]=@"3";
        }else if (power==10){
            params[@"from_type"]=@"4";
        }
        else{
            params[@"from_type"]=@"2";
        }
    }
    [UIActivityIndicatorView appearanceWhenContainedIn:[UINavigationBar class], nil].color = tintblue;
    [self.navigationItem startAnimatingAt:ANNavBarLoaderPositionCenter];
    
    [PostUitls Post:messageurl parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            NSArray *array=[MessageListMode objectArrayWithKeyValuesArray:dict[@"data"]];
            [self.datalist addObjectsFromArray:array];
            [self.tableView reloadData];
        }
        if (self.datalist.count>0) {
            NSInteger count=0;
            for (MessageListMode *mode in self.datalist) {
                count+=[mode.num integerValue];
            }
            [XHUserDeflaut setInteger:count forKey:NotReadState];
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
            
        }else{
            [XHUserDeflaut setInteger:0 forKey:NotReadState];
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        }
        [self.navigationItem stopAnimating];
        
    } failure:^(NSError *error) {
        [self.navigationItem stopAnimating];
        [XHUserDeflaut setInteger:0 forKey:NotReadState];
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (self.datalist.count==0) {
        [self.notiem show];
    }else{
        [self.notiem hide];
    }
    return self.datalist.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    MessageListTableViewCell *cell=[MessageListTableViewCell cellWithTablview:tableView];
    
    MessageListMode *mode=self.datalist[indexPath.row];
    cell.mode=mode;
    return cell;
    
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageDetailTableViewController *messagedetail=[[MessageDetailTableViewController alloc]init];
    
    MessageListMode *mode=self.datalist[indexPath.row];
    messagedetail.toid=mode.toId;
    messagedetail.totype=mode.toType;
    messagedetail.toico=mode.ico;
    messagedetail.navigationItem.title=mode.truename;
    [self.navigationController pushViewController:messagedetail animated:YES];
    
}

@end
